import { createActions, handleActions } from 'redux-actions';
import { getRoleList } from '@api/role';
import { get } from 'lodash';

const initState = {
  roles: []
};

export const actions = createActions({
  GETROLELIST: params => {
    return (
      getRoleList(params)
        .then(res => {
          const result = get(res, 'data.result');
          if (result) {
            return Promise.resolve(res);
          } else {
            return Promise.reject('获取角色列表失败');
          }
        })
        // eslint-disable-next-line
        .catch(() => console.error('获取角色列表失败'))
    );
  }
});

const reducer = handleActions(
  {
    GETROLELIST: (state, actions) => {
      const roles = get(actions.payload, 'data.data.roles', []);
      return {
        ...state,
        roles
      };
    }
  },
  initState
);

export default reducer;
